package com.puente.hook;


import com.liferay.portal.ModelListenerException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.model.Resource;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.model.ResourcePermission;
import com.liferay.portal.model.Role;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.service.PermissionLocalServiceUtil;
import com.liferay.portal.service.ResourceLocalServiceUtil;
import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
import com.liferay.portal.service.ResourcePermissionServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFolder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
//import com.liferay.portlet.documentlibrary.model.DLFolder;
/**
 *
 * @author james Stuart Milne & Joaquin Cabal
 * Updated by Meanson Wang / meansonw@gmail.com @ 20110429
 */
public class FolderHook implements ModelListener {
    private DLFolder createdFolder;
    public void onAfterCreate(Object model) throws ModelListenerException {
        //Add your implementation here
        com.liferay.portlet.documentlibrary.model.DLFolder mdlObj 
                = (com.liferay.portlet.documentlibrary.model.DLFolder) model;
        createdFolder=mdlObj;
    }

    public void onAfterAddAssociation(Object arg0, String arg1, Object arg2) throws ModelListenerException {
        //Add your implementation here
        System.out.println("LLEGUE ACA");
    }

    public void onAfterRemove(Object model) throws ModelListenerException {
        //Add your implementation here
    }

    public void onAfterRemoveAssociation(Object arg0, String arg1, Object arg2) throws ModelListenerException {
        //Add your implementation here
    }

    public void onAfterUpdate(Object model) throws ModelListenerException {
        try {
            //Add your implementation here
            com.liferay.portlet.documentlibrary.model.DLFolder parentFolder = (com.liferay.portlet.documentlibrary.model.DLFolder) model;
//            List<DLFolder> folderList = parentFolder.getAncestors();
//
//            Iterator<DLFolder> folderListIterator =folderList.iterator();
//            while(folderListIterator.hasNext()){
//                DLFolder folderEntry=folderListIterator.next();
//                if(folderEntry.)
//            }
            DLFolder addedFolderEntry = createdFolder;
            if (parentFolder != null && createdFolder!=null) {
                Resource resource = ResourceLocalServiceUtil.getResource(parentFolder.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(parentFolder.getFolderId()));

                // List<Role> roles = ResourceAction.getRoles(parentFolder.getCompanyId(), parentFolder.getGroupId(), resource);
                //Map values = RoleLocalServiceUtil.getResourceRoles(parentFolder.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(resource.getPrimKey()));
                List values = ResourcePermissionLocalServiceUtil.getResourcePermissions(parentFolder.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(resource.getPrimKey()));
                
                //Resource resourceFileEntry = ResourceLocalServiceUtil.getResource(addedFolderEntry.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(addedFolderEntry.getFolderId()));

                // Remove default permissions
             	 Role guestRole =RoleLocalServiceUtil.getRole(parentFolder.getCompanyId(), "Guest");
             	 ResourcePermissionLocalServiceUtil.removeResourcePermissions(parentFolder.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, guestRole.getRoleId(), ActionKeys.VIEW);
             	 Role commRole =RoleLocalServiceUtil.getRole(parentFolder.getCompanyId(), "Community Member");
             	 ResourcePermissionLocalServiceUtil.removeResourcePermissions(parentFolder.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, commRole.getRoleId(), ActionKeys.VIEW);
             	 ResourcePermissionLocalServiceUtil.removeResourcePermissions(parentFolder.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, commRole.getRoleId(), ActionKeys.ADD_DOCUMENT);
             	 ResourcePermissionLocalServiceUtil.removeResourcePermissions(parentFolder.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, commRole.getRoleId(), ActionKeys.ADD_SHORTCUT);
             	 ResourcePermissionLocalServiceUtil.removeResourcePermissions(parentFolder.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, commRole.getRoleId(), ActionKeys.ADD_SUBFOLDER);
             	
             	
                
                
                for (int i=0;i<values.size();i++) {
                	ResourcePermission resourcePermission=(ResourcePermission) values.get(i);
                	
                	/* 	for (Iterator iterator3=actionIds1.iterator();iterator3.hasNext();) {
                			Object obj=iterator3.next();
                			System.out.print("actionId:"+obj.toString());
                		}
                		
                		*/
                	//PermissionLocalServiceUtil.setRolePermissions(p.getRoleId(), p., resourceFileEntry.getResourceId());
                	//Role role = RoleLocalServiceUtil.getRole(addedFolderEntry.getCompanyId(), (String) value.getKey());
                	Role role=RoleLocalServiceUtil.getRole(resourcePermission.getRoleId());


                	//String actionids[] = {"VIEW"};
                	//Resource res = ResourceLocalServiceUtil.getResource(addedFolderEntry.getCompanyId(),DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, ""+pk);                	
                	

                	String[] actionIds = new String[2] ;
                	actionIds[0]=ActionKeys.ACCESS;
                	actionIds[1]=ActionKeys.VIEW;

                	if (!role.getName().equals("Owner")) {
                		ResourcePermissionServiceUtil.setIndividualResourcePermissions(addedFolderEntry.getGroupId(), addedFolderEntry.getCompanyId(), DLFolder.class.getName(), new Long(addedFolderEntry.getPrimaryKey()).toString(), role.getRoleId(), actionIds);
                	//PermissionLocalServiceUtil.setRolePermissions(p.getRoleId(),actionIds, res.getResourceId());
                	//PermissionLocalServiceUtil.setRolePermissions(p.getRoleId(), addedFolderEntry.getCompanyId(), DLFolder.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(addedFolderEntry.getFolderId()), actionIds);
                	}
                	else {
                		ResourcePermissionServiceUtil.setIndividualResourcePermissions(addedFolderEntry.getGroupId(), addedFolderEntry.getCompanyId(), DLFolder.class.getName(), new Long(addedFolderEntry.getPrimaryKey()).toString(), role.getRoleId(), new String[] {ActionKeys.ACCESS,ActionKeys.DELETE,ActionKeys.VIEW,ActionKeys.UPDATE,ActionKeys.PERMISSIONS,ActionKeys.ADD_DOCUMENT,ActionKeys.ADD_SHORTCUT,ActionKeys.ADD_SUBFOLDER});
                	}
                	                
                	
                }
                /*
                for (Iterator iterator = values.entrySet().iterator(); iterator.hasNext();) {
                    Map.Entry value = (Map.Entry) iterator.next();
                    List<String> actionIds = (List<String>) value.getValue();
                    for (Iterator iterator2 = actionIds.iterator(); iterator2.hasNext();) {
                        Object obj = iterator2.next();
                        if (!"VIEW".equalsIgnoreCase((String) obj) && !"DELETE".equalsIgnoreCase((String) obj)) {
                            iterator2.remove();
                        }
                    }
                    String[] actions = new String[actionIds.size()];
                    for (int i = 0; i < actionIds.size(); i++) {
                        actions[i] = actionIds.get(i);
                    }
                    Role role = RoleLocalServiceUtil.getRole(addedFolderEntry.getCompanyId(), (String) value.getKey());
                    PermissionLocalServiceUtil.setRolePermissions(role.getRoleId(), actions, resourceFileEntry.getResourceId());
                } 
                */
            }
        } catch (PortalException ex) {
        	//ex.printStackTrace();
            Logger.getLogger(FolderHook.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SystemException ex) {
            Logger.getLogger(FolderHook.class.getName()).log(Level.SEVERE, null, ex);
        }
        createdFolder=null;
    }

    public void onBeforeAddAssociation(Object arg0, String arg1, Object arg2) throws ModelListenerException {
        //Add your implementation here
    }

    public void onBeforeCreate(Object model) throws ModelListenerException {
        //Add your implementation here
    }

    public void onBeforeRemove(Object model) throws ModelListenerException {
        //Add your implementation here
    }

    public void onBeforeRemoveAssociation(Object arg0, String arg1, Object arg2) throws ModelListenerException {
        //Add your implementation here
    }

    public void onBeforeUpdate(Object model) throws ModelListenerException {
        //Add your implementation here
    }

}